const { modelNames } = require('mongoose')

module.exports = app => {
  const express = require('express')
  const Category = require('../../models/Category')
  const Subject = require('../../models/Subject')
  const AdminUser = require('../../models/AdminUser')
const StudentUser = require('../../models/StudentUser')
const Test = require('../../models/Test')
const Answer = require('../../models/Answer')
  const jwt = require('jsonwebtoken')
  const assert = require('http-assert')
  const router = express.Router({
    mergeParams: true
  })
  const resourceWall = require('../../middleware/resource')
  const authWall = require('../../middleware/auth')
 
  router.post('/', async(req,res) => {
  const model = await req.model.create(req.body)
  res.send(model)
  })

  router.put('/:id', async(req,res) => {
    const model = await req.model.findByIdAndUpdate(req.params.id, req.body)
    res.send(model)
    })


    router.get('/:id', async(req,res) => {
      const model = await req.model.findById(req.params.id) 
      res.send(model)
      })


      router.delete('/:id', async(req,res) => {
        const model = await req.model.findByIdAndDelete(req.params.id, req.body)
        res.send(model)
        })

  router.get('/', async(req,res) => {
    const queryOptions = {}
    if (req.model.modelName === 'Subject' || 'Test') {
      queryOptions.populate = 'categories'
    }
    const model = await req.model.find().setOptions(queryOptions)
    res.send(model)
  })

  app.use('/admin/api/rest/:resource', authWall(), resourceWall(), router)
//  分类
  const genre = express.Router()
  genre.get('/genre/subject', async(req,res) => {
    const model = await Category.find()
    res.send(model)
  } )

  genre.get('/genre/test', async(req,res) => {
    const model = await Subject.find().populate('categories')
    res.send(model)
  } )


  app.use('/admin/api', genre)
  
  const multer = require('multer')
  const upload = multer({dest: __dirname + '/../../uploads'})
  app.use('/admin/api/upload', authWall(), upload.single('file'),async (req,res) => {
   const file = req.file
   file.url = `http://www.lihuamao.top/uploads/${file.filename}`
   res.send(file)
  })

  app.use('/admin/api/login' ,async (req,res) => {
    const {userName, password} = req.body
   
    const user = await AdminUser.findOne({userName}).select('+password')
    assert(user,422, '用户名不存在')

    const isTrue = require('bcrypt').compareSync(password, user.password)
    assert(isTrue, 422, '密码错误')
   
    const token = jwt.sign({id: user._id}, app.get('secret'))
    res.send({token})
  })
// student message
 const student = express.Router()
 student.post('/register', async(req,res) => {
   const {username ,password,passwordSure} = req.body
   var regname =  /^[a-zA-Z0-9_-]{4,12}$/
   var regpwd = /^[a-zA-Z0-9_-]{6,16}$/
   const name =  regname.test(username)
   assert(name, 422,'请输入4-12位字母或数字的用户名')

   const pass = regpwd.test(password)
   assert(pass, 422, '请输入6-16位字母或数字的密码')
   if (password !== passwordSure) {
     const passFalse = password !== passwordSure
   assert(!passFalse, 422, '两次密码不一样哦~')
   }

   const user = await StudentUser.findOne({username})
    assert(!user,422, '该用户名已被注册，换一个叭~')

   const model = await StudentUser.create(req.body)
   res.send(model)
 })

 student.post('/login', async(req,res) => {
   const {username, password} = req.body
   
    const user = await StudentUser.findOne({username})
    assert(user,422, '用户名不存在, 请先注册一下叭~')

    const isTrue = password  === user.password
    assert(isTrue, 422, '密码不对哦，在试一下叭~')
   
    const token = jwt.sign({id: user._id}, app.get('secret'))
    res.send({token})
 })
 student.post('/login/user', async(req,res) => {
  const {username} = req.body

   res.send(username)
})
 app.use('/student/api', student)

 const students = express.Router()
 students.get('/students', async(req,res) => {
  const model = await StudentUser.find()
  res.send(model)
})
students.delete('/students/:id', async(req,res) => {
  const model = await StudentUser.findByIdAndDelete(req.params.id, req.body)
  res.send(model)
})
students.get('/message',async(req,res) => {
const model = await Test.find()
res.send(model)

})

students.post('/student/answer', async(req,res) => {
  const model = await Answer.create(req.body)
  res.send(model)
  })

students.put('/student/answer/:id', async(req,res) => {
    const model = await Answer.findByIdAndUpdate(req.params.id, req.body)
    res.send(model)
    })

students.get('/student/answer', async(req,res) => {
  const model = await Answer.find()
  res.send(model)
})
students.delete('/student/answer/:id', async(req,res) => {
  const model = await Answer.findByIdAndDelete(req.params.id, req.body)
  res.send(model)
})

students.get('/student/answer/:id', async(req,res) => {
  const model = await Answer.findById(req.params.id)
  res.send(model)
})

students.get('/test/:id', async(req,res) => {
  console.log(req.params.id);
    const model = await Test.findById(req.params.id)
    res.send(model)
  })

  students.post('/test/:id', async(req,res) => {
    const model = await Test.findById(req.params.id)
    res.send(model)
  })
  
 app.use('/admin/api',students)

  app.use(async (err,req,res,next) => {
    res.status(err.statusCode || 500).send({
      message: err.message
    })
  })
}
